package com.qk.management.aop;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.qk.common.util.Result;
import com.qk.management.anno.Cacheable;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.concurrent.TimeUnit;


@Slf4j
@Aspect
@Component
@SuppressWarnings("all")
public class CacheableAspect {

    @Autowired
    private StringRedisTemplate redisClient;

    @Pointcut("@annotation(com.qk.management.aop.Cacheable)")
    public void pt() {
    }

    @Around("pt()")
    public Object cacheable(ProceedingJoinPoint pjp) throws Throwable {

        Object result = null;
        String redisKey = null;
        long expireTime = 0L;
        TimeUnit expireTimeUnit = null;
        try {
            Class<?> aClass = pjp.getTarget().getClass();
            String name = pjp.getSignature().getName();
            Method method = aClass.getMethod(name);
            Cacheable annotation = method.getAnnotation(Cacheable.class);
            redisKey = annotation.redisKey() + name;
            expireTime = annotation.redisKeyExpireTime();
            expireTimeUnit = annotation.redisKeyExpireTimeUnit();
            String jsonStr = redisClient.opsForValue().get(redisKey);
            if (ObjectUtil.isNotEmpty(jsonStr)) {
                return JSONUtil.toBean(jsonStr, method.getReturnType());
            }
        } catch (Exception e) {
            log.error("获取缓存注解异常", e.getMessage());
        }
        try {
            result = pjp.proceed();
        } catch (Throwable e) {
            result= Result.error("您的操作有问题，请稍后再试！");
        }
        try {
            redisClient.opsForValue().set(redisKey, JSONUtil.toJsonStr(result), expireTime, expireTimeUnit);
        } catch (Exception e) {
            log.error("添加缓存异常:{}", e);
        }
        return result;
    }
}
